<?php

namespace App\Console\Commands;

use App\Http\Service\DeviceService;
use App\Model\Bill;
use App\Model\DeviceTask;
use Illuminate\Console\Command;

class DeviceAutoStartCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'device:auto-start';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '满足条件后自动合闸';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $tasks = DeviceTask::query()->whereNull('run_at')
            ->with('contract','contract.house', 'contract.house.device')
            ->get();
        foreach ($tasks as $task)
        {
            // 找出所有预期账单
            $bills = Bill::query()->where('is_close', 0)
                ->where('pay_date', '<', now()->toDateString())
                ->where('is_paid', 0)
                ->orderByDesc('id')
                ->where('contract_id', $task->contract_id)
                ->with('business', 'business.conf', 'contract', 'house', 'house.device')
                ->count();

            if (!$bills && $task->contract && $task->contract->house) {
                foreach ($task->contract->house->device as $d) {
                    $this->handleDeviceStart($d->mac);
                }
            }
            $task->run_at = now()->toDateTimeString();
            $task->save();
        }
    }

    public function handleDeviceStart($mac)
    {
        $service = app()->make(DeviceService::class);
        $service->start($mac);
    }
}
